package database

import (
	"domain-system/models"
	"fmt"
	"strings"

	"github.com/glebarez/sqlite"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func Init(databaseURL string) (*gorm.DB, error) {
	var err error
	var db *gorm.DB

	if strings.Contains(databaseURL, ".db") || strings.Contains(databaseURL, "sqlite") || databaseURL == ":memory:" {
		// SQLite 数据库（包括内存数据库）
		db, err = gorm.Open(sqlite.Open(databaseURL), &gorm.Config{})
	} else {
		// MySQL 数据库
		db, err = gorm.Open(mysql.Open(databaseURL), &gorm.Config{})
	}

	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %v", err)
	}

	// 设置全局DB变量
	DB = db

	// 自动迁移数据库表
	err = db.AutoMigrate(
		// 原有模型
		&models.Payment{},
		&models.GroupApplication{},
		// 新增帖子相关模型
		&models.User{},
		&models.Circle{},
		&models.Tag{},
		&models.Post{},
		&models.PostTag{},
		&models.Comment{},
		&models.Like{},
		&models.Follow{},
	)
	if err != nil {
		return nil, fmt.Errorf("failed to migrate database: %v", err)
	}

	// 初始化默认数据
	if err := initDefaultData(); err != nil {
		return nil, fmt.Errorf("failed to initialize default data: %v", err)
	}

	return db, nil
}

// initDefaultData 初始化默认数据
func initDefaultData() error {
	// 创建默认圈子
	defaultCircles := []models.Circle{
		{
			Name:        "城市圈",
			Type:        models.CircleTypeCity,
			CountryCode: "CN",
			CityCode:    "BJ",
			Description: "北京用户交流圈",
			IsActive:    true,
		},
		{
			Name:        "国家圈",
			Type:        models.CircleTypeCountry,
			CountryCode: "CN",
			Description: "中国用户交流圈",
			IsActive:    true,
		},
		{
			Name:        "全球圈",
			Type:        models.CircleTypeGlobal,
			Description: "全球用户交流圈",
			IsActive:    true,
		},
	}

	for _, circle := range defaultCircles {
		var existingCircle models.Circle
		if err := DB.Where("name = ? AND type = ?", circle.Name, circle.Type).First(&existingCircle).Error; err == gorm.ErrRecordNotFound {
			if err := DB.Create(&circle).Error; err != nil {
				return err
			}
		}
	}

	// 在初始化标签的地方，为每个标签指定对应的圈子ID
	defaultTags := []models.Tag{
		// 全球圈标签 (circle_id = 1)
		{Name: "科技", CircleID: 1, Color: "#4ECDC4", IsActive: true},
		{Name: "生活", CircleID: 1, Color: "#FF6B6B", IsActive: true},
		{Name: "旅行", CircleID: 1, Color: "#45B7D1", IsActive: true},
		// 国家圈标签 (circle_id = 2)
		{Name: "新闻", CircleID: 2, Color: "#96CEB4", IsActive: true},
		{Name: "文化", CircleID: 2, Color: "#FFEAA7", IsActive: true},
		{Name: "美食", CircleID: 2, Color: "#DDA0DD", IsActive: true},
		// 城市圈标签 (circle_id = 3)
		{Name: "活动", CircleID: 3, Color: "#98D8C8", IsActive: true},
		{Name: "本地", CircleID: 3, Color: "#F7DC6F", IsActive: true},
		{Name: "商业", CircleID: 3, Color: "#BB8FCE", IsActive: true},
	}

	for _, tag := range defaultTags {
		var existingTag models.Tag
		if err := DB.Where("name = ?", tag.Name).First(&existingTag).Error; err == gorm.ErrRecordNotFound {
			if err := DB.Create(&tag).Error; err != nil {
				return err
			}
		}
	}

	return nil
}
